package com.iot.service.mqtt.service.message;

import com.iot.service.mqtt.service.StoreStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * @Author: hszhou
 * @Date: 2025/4/23 9:05
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "mqtt", name = "store-strategy", havingValue = StoreStrategy.REDIS)
@Slf4j
public class RedisMessageServiceImpl implements IMessage {


    private final static String ID_KEY = "ID";

    private final ReactiveRedisTemplate<String, Object> reactiveRedisTemplate;

    private static final String ID_RESET_SCRIPT = "local current = redis.call('INCR', KEYS[1])\n" +
            "if current > " +MAX_ID+
            " then\n" +
            "redis.call('SET', KEYS[1], 0)\n" +
            "return 0\n" +
            "else\n" +
            "return current\n" +
            "end";
    DefaultRedisScript<Long> script = new DefaultRedisScript<>(ID_RESET_SCRIPT, Long.class);
    @Override
    public Long getMessageId() {
        return reactiveRedisTemplate.execute(script, Collections.singletonList(ID_KEY)).singleOrEmpty().block();
    }
}
